<?php

/**
 * This is the model class for table "OVE_RH_ITEM".
 *
 * The followings are the available columns in table 'OVE_RH_ITEM':
 * @property double $ID
 * @property double $TIPO_ID
 * @property string $TITULO
 * @property double $INICIO_ESCALA
 * @property double $FIM_ESCALA
 */
class Item extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'OVE_RH_ITEM';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
//            array('TIPO_ID, TITULO, INICIO_ESCALA, FIM_ESCALA', 'required'),
//            array('TIPO_ID, INICIO_ESCALA, FIM_ESCALA', 'numerical'),
            array('TITULO', 'length', 'max'=>200),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('ID, TIPO_ID, TITULO, INICIO_ESCALA, FIM_ESCALA', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'ID' => 'ID',
            'TIPO_ID' => 'Tipo',
            'TITULO' => 'Titulo',
            'INICIO_ESCALA' => 'Inicio Escala',
            'FIM_ESCALA' => 'Fim Escala',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('ID',$this->ID);
        $criteria->compare('TIPO_ID',$this->TIPO_ID);
        $criteria->compare('TITULO',$this->TITULO,true);
        $criteria->compare('INICIO_ESCALA',$this->INICIO_ESCALA);
        $criteria->compare('FIM_ESCALA',$this->FIM_ESCALA);

        return new CActiveDataProvider($this, array(
                                                   'criteria'=>$criteria,
                                              ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Item the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * Adiciona o id que vem do sequencial
     */
    protected function beforeSave()
    {
        if(empty($this->ID))
        {
            if(parent::beforeSave())
            {
                $connection=Yii::app()->db;
                $sql = "select {$this->tableName()}_SEQ.nextVal from dual";
                $result = $connection->createCommand($sql)->queryRow();
                $this->ID = $result['NEXTVAL'];
            }
        }
        return $this->ID;
    }

    public function saveMany($itens,$option)
    {
        if(is_array($itens))
        {
            if(count($itens) > 1)
            {
                $escala_inicio = isset($itens["ESCALA_INCIO"])?$itens["ESCALA_INCIO"]:'';
                $escala_fim = isset($itens["ESCALA_FIM"])?$itens["ESCALA_FIM"]:'';
                unset($itens["ESCALA_INCIO"]);
                unset($itens["ESCALA_FIM"]);
                foreach($itens as $keys=>$values)
                {
                    $idTipo = Tipo::model()->getTipoId(strtolower($keys));
                    $modelItem = new Item;

                    $modelItem->TITULO = $values;
                    if(empty($idTipo)){
                        $modelItem->INICIO_ESCALA = $escala_inicio;
                        $modelItem->FIM_ESCALA = $escala_fim;
                    }
                    $modelItem->TIPO_ID = $idTipo!=null?$idTipo:'';
                    if($modelItem->save())
                    {
                        PerguntaItem::model()->saveAll(array('PERGUNTA_ID'=>$option["PERGUNTA_ID"],'FORMULARIO_ID'=>$option["FORMULARIO_ID"],'TIPOPERGUNTA_ID'=>$idTipo!=null? $idTipo: $option["TIPOPERGUNTA_ID"],'ITEM_ID'=>$modelItem->ID));
                    }
                }
            }
            else
            {
                /**
                 * Salva os item que forem do tipo text ou textarea
                 */
                $modelItem = new Item;
                $modelItem->TIPO_ID = $option["TIPOPERGUNTA_ID"];
                if($modelItem->save())
                {
                    PerguntaItem::model()->saveAll(array('PERGUNTA_ID'=>$option["PERGUNTA_ID"],'FORMULARIO_ID'=>$option["FORMULARIO_ID"],'TIPOPERGUNTA_ID'=>$option["TIPOPERGUNTA_ID"],'ITEM_ID'=>$modelItem->ID));
                }

            }
        }
        return true;
    }

    public function updateItemMany($itens,$option)
    {
        /*echo "<pre>";
        print_r($option);
        echo "</pre>";
        exit;*/
        if(is_array($itens))
        {
            if(count($itens) > 1 || isset($itens['UPDATE']))
            {
                $escala_inicio = isset($itens["ESCALA_INICIO"])?$itens["ESCALA_INICIO"]:'';
                $escala_fim = isset($itens["ESCALA_FIM"])?$itens["ESCALA_FIM"]:'';
                unset($itens["ESCALA_INICIO"]);
                unset($itens["ESCALA_FIM"]);
                foreach($itens as $keys=>$values)
                {
                    if($keys === 'UPDATE')
                    {
                        foreach($values as $item)
                        {
                            if(isset($item['TITULO']) || isset($item['TEXT']))
                            {
                                $idTipo = isset($item['TEXT'])?'TEXT':'';
                                $idTipo = Tipo::model()->getTipoId(strtolower($idTipo));

                                $modelItem = $this->loadModel($item["ID"]);


                                if(isset($item['TITULO']))
                                {
                                    $modelItem->TITULO = $item['TITULO'];
                                }
                                elseif(isset($item['TEXT']))
                                {
                                    $modelItem->TITULO = $item['TEXT'];
                                }

                                $modelItem->INICIO_ESCALA = $escala_inicio;
                                $modelItem->FIM_ESCALA = empty($escala_fim)?'':$escala_fim;
                                $modelItem->TIPO_ID = empty($idTipo)?'':$idTipo;
                                $modelItem->save();
                            }
                            else
                            {
//                                echo "Deletar ITEM".$item["ID"]." PERGUNTA ".$option['PERGUNTA_ID']." <br/>";
//                                echo "Deletar ITEM".$item["ID"]." <br/>";
                                PerguntaItem::model()->deleteAllPerguntaItem($item["ID"],$option['PERGUNTA_ID']);
                                $this->deleteItemMany($item["ID"]);
                            }

                        }
                    }
                    else
                    {
                        $idTipo = Tipo::model()->getTipoId(strtolower($keys));
                        $modelItem = new Item;

                        $modelItem->TITULO = $values;
                        if(empty($idTipo)){
                            $modelItem->INICIO_ESCALA = $escala_inicio;
                            $modelItem->FIM_ESCALA = $escala_fim;
                        }
                        $modelItem->TIPO_ID = $idTipo!=null?$idTipo:'';

//                        echo "INSERT -> ".$modelItem->TITULO."=TITULO".$modelItem->INICIO_ESCALA."=INCIO".$modelItem->FIM_ESCALA."=FIM".$modelItem->TIPO_ID."=TIPO<BR/>";
                        if($modelItem->save())
                        {
                            PerguntaItem::model()->saveAll(array('PERGUNTA_ID'=>$option["PERGUNTA_ID"],'FORMULARIO_ID'=>$option["FORMULARIO_ID"],'TIPOPERGUNTA_ID'=>$idTipo!=null? $idTipo: $option["TIPOPERGUNTA_ID"],'ITEM_ID'=>$modelItem->ID));
                        }
                    }
                }
            }
        }
//        exit;
        return true;
    }

    private function deleteItemMany($id)
    {
       $this->loadModel($id)->delete();
    }

    private function loadModel($id)
    {
        $model = Item::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    public function escalaInicio()
    {
        return CHtml::listOptions('tipo',array('0'=>'0'));
    }
}
